package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/download.do")
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getParameter("path");
        resp.setContentType("UTF-8");
        File file = new File("D:\\桌面文件\\壁纸\\壁纸 csxy\\csxygqdnbz\\" + path);
        if (!file.exists()){
            resp.getWriter().write("您要下载的内容不存在！");
            return;
        }
        path = new String(path.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

        resp.addHeader("content-disposition", "attachment;filename=" + path);
        ServletOutputStream outputStream = resp.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(file);
        int length;
        byte[] bytes = new byte[1024];
        while((length=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,length);
            outputStream.flush();
        }
        outputStream.close();
        fileInputStream.close();
    }
}
